#!/bin/bash

# Feng Admin 环境配置辅助脚本
# 交互式创建和配置前后端 .env 文件

# 颜色定义
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# 清屏
clear

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}  Feng Admin - 环境配置向导${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

# 获取项目根目录
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
PROJECT_ROOT="$( cd "$SCRIPT_DIR/.." && pwd )"
BACKEND_DIR="$PROJECT_ROOT/apps/backend"
FRONTEND_DIR="$PROJECT_ROOT/apps/frontend"

# 生成随机密钥的函数
generate_secret_key() {
    python3 -c "import secrets; print(secrets.token_hex(32))" 2>/dev/null || \
    python -c "import secrets; print(secrets.token_hex(32))" 2>/dev/null || \
    openssl rand -hex 32 2>/dev/null || \
    echo "$(date +%s | sha256sum | base64 | head -c 64)"
}

# 检查端口是否被占用
check_port() {
    local port=$1
    if command -v lsof &> /dev/null; then
        lsof -i :$port &> /dev/null
        return $?
    elif command -v netstat &> /dev/null; then
        netstat -tuln | grep ":$port " &> /dev/null
        return $?
    else
        return 1
    fi
}

# 获取可用端口
get_available_port() {
    local start_port=$1
    local port=$start_port
    
    while check_port $port; do
        port=$((port + 1))
        if [ $port -gt 65535 ]; then
            echo "0"
            return
        fi
    done
    
    echo "$port"
}

# ==================== 后端环境配置 ====================

echo -e "${CYAN}[1/2] 配置后端环境变量${NC}"
echo ""

BACKEND_ENV="$BACKEND_DIR/.env"

if [ -f "$BACKEND_ENV" ]; then
    echo -e "${YELLOW}检测到已存在后端 .env 文件${NC}"
    read -p "是否覆盖现有配置? (y/N): " overwrite
    if [[ ! $overwrite =~ ^[Yy]$ ]]; then
        echo -e "${GREEN}✓ 保留现有后端配置${NC}"
        SKIP_BACKEND=true
    fi
fi

if [ "$SKIP_BACKEND" != true ]; then
    echo -e "${BLUE}请选择环境模式:${NC}"
    echo "  1. 开发环境 (development)"
    echo "  2. 生产环境 (production)"
    read -p "请选择 (1-2) [1]: " env_mode
    env_mode=${env_mode:-1}

    if [ "$env_mode" = "2" ]; then
        FLASK_ENV="production"
        FLASK_DEBUG="False"
        echo ""
        echo -e "${YELLOW}⚠️  生产环境模式${NC}"
    else
        FLASK_ENV="development"
        FLASK_DEBUG="True"
        echo ""
        echo -e "${GREEN}✓ 开发环境模式${NC}"
    fi

    echo ""
    echo -e "${BLUE}生成安全密钥...${NC}"
    SECRET_KEY=$(generate_secret_key)
    JWT_SECRET_KEY=$(generate_secret_key)
    echo -e "${GREEN}✓ 密钥已生成${NC}"

    echo ""
    read -p "JWT Token 过期时间(小时) [24]: " jwt_expires
    jwt_expires=${jwt_expires:-24}

    echo ""
    read -p "后端端口 [5001]: " backend_port
    backend_port=${backend_port:-5001}
    
    # 检查后端端口是否被占用
    if check_port $backend_port; then
        echo -e "${YELLOW}⚠️  端口 $backend_port 已被占用${NC}"
        available_port=$(get_available_port $backend_port)
        if [ "$available_port" != "0" ]; then
            read -p "使用可用端口 $available_port ? (Y/n): " use_available
            if [[ ! $use_available =~ ^[Nn]$ ]]; then
                backend_port=$available_port
            else
                read -p "请输入其他端口: " backend_port
            fi
        else
            read -p "请输入其他端口: " backend_port
        fi
    fi

    echo ""
    if [ "$FLASK_ENV" = "production" ]; then
        echo -e "${YELLOW}请配置 CORS 允许的域名${NC}"
        echo "格式: https://domain1.com,https://domain2.com"
        read -p "CORS_ORIGINS: " cors_origins
        if [ -z "$cors_origins" ]; then
            cors_origins="*"
            echo -e "${YELLOW}⚠️  使用通配符 * (不推荐用于生产环境)${NC}"
        fi
    else
        cors_origins="*"
        echo -e "${GREEN}✓ 开发环境使用通配符 CORS${NC}"
    fi

    # 创建后端 .env 文件
    cat > "$BACKEND_ENV" << EOF
# Feng Admin 后端环境变量配置
# 由环境配置向导自动生成于 $(date)

# ==================== 应用环境 ====================
FLASK_ENV=$FLASK_ENV
FLASK_DEBUG=$FLASK_DEBUG

# ==================== 安全密钥 ====================
SECRET_KEY=$SECRET_KEY
JWT_SECRET_KEY=$JWT_SECRET_KEY

# ==================== JWT 配置 ====================
JWT_ACCESS_TOKEN_EXPIRES=$jwt_expires
JWT_REFRESH_TOKEN_EXPIRES=30

# ==================== CORS 配置 ====================
CORS_ORIGINS=$cors_origins

# ==================== 缓存配置 ====================
GITHUB_TRENDING_CACHE_HOURS=4

# ==================== 日志配置 ====================
LOG_LEVEL=INFO

# ==================== 服务器配置 ====================
BACKEND_HOST=0.0.0.0
BACKEND_PORT=$backend_port
EOF

    echo ""
    echo -e "${GREEN}✓ 后端环境配置已创建: $BACKEND_ENV${NC}"
fi

echo ""
echo ""

# ==================== 前端环境配置 ====================

echo -e "${CYAN}[2/2] 配置前端环境变量${NC}"
echo ""

FRONTEND_ENV="$FRONTEND_DIR/.env"

if [ -f "$FRONTEND_ENV" ]; then
    echo -e "${YELLOW}检测到已存在前端 .env 文件${NC}"
    read -p "是否覆盖现有配置? (y/N): " overwrite
    if [[ ! $overwrite =~ ^[Yy]$ ]]; then
        echo -e "${GREEN}✓ 保留现有前端配置${NC}"
        SKIP_FRONTEND=true
    fi
fi

if [ "$SKIP_FRONTEND" != true ]; then
    echo -e "${BLUE}前端配置:${NC}"
    echo ""
    
    read -p "前端端口 [5173]: " frontend_port
    frontend_port=${frontend_port:-5173}
    
    # 检查前端端口是否被占用
    if check_port $frontend_port; then
        echo -e "${YELLOW}⚠️  端口 $frontend_port 已被占用${NC}"
        available_port=$(get_available_port $frontend_port)
        if [ "$available_port" != "0" ]; then
            read -p "使用可用端口 $available_port ? (Y/n): " use_available
            if [[ ! $use_available =~ ^[Nn]$ ]]; then
                frontend_port=$available_port
            else
                read -p "请输入其他端口: " frontend_port
            fi
        else
            read -p "请输入其他端口: " frontend_port
        fi
    fi
    
    echo ""
    echo -e "${BLUE}后端 API 地址配置:${NC}"
    echo ""
    
    if [ "$FLASK_ENV" = "production" ]; then
        echo "  示例: https://api.yourdomain.com:${backend_port}"
        read -p "请输入后端 API 地址: " api_url
        if [ -z "$api_url" ]; then
            api_url="http://localhost:${backend_port}"
            echo -e "${YELLOW}⚠️  使用默认地址${NC}"
        fi
    else
        api_url="http://localhost:${backend_port}"
        echo -e "${GREEN}✓ 使用本地开发地址: $api_url${NC}"
    fi

    # 创建前端 .env 文件
    cat > "$FRONTEND_ENV" << EOF
# Feng Admin 前端环境变量配置
# 由环境配置向导自动生成于 $(date)

# ==================== API 配置 ====================
VITE_API_BASE_URL=$api_url

# ==================== 服务器配置 ====================
VITE_SERVER_HOST=0.0.0.0
VITE_SERVER_PORT=$frontend_port

# ==================== 应用配置 ====================
VITE_APP_TITLE=Feng Admin
VITE_APP_VERSION=1.0.0

# ==================== 功能开关 ====================
VITE_ENABLE_DEV_TOOLS=true
VITE_ENABLE_LOGGING=true
EOF

    echo ""
    echo -e "${GREEN}✓ 前端环境配置已创建: $FRONTEND_ENV${NC}"
fi

echo ""
echo ""
echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}  环境配置完成！${NC}"
echo -e "${GREEN}========================================${NC}"
echo ""

if [ "$SKIP_BACKEND" != true ]; then
    echo -e "后端配置文件: ${CYAN}$BACKEND_ENV${NC}"
    echo -e "  后端端口: ${CYAN}$backend_port${NC}"
fi

if [ "$SKIP_FRONTEND" != true ]; then
    echo -e "前端配置文件: ${CYAN}$FRONTEND_ENV${NC}"
    echo -e "  前端端口: ${CYAN}$frontend_port${NC}"
    echo -e "  API 地址: ${CYAN}$api_url${NC}"
fi

echo ""
echo -e "${YELLOW}提示:${NC}"
echo "  - 可以手动编辑 .env 文件进行更多配置"
echo "  - 查看 env.example 文件了解所有可用选项"
echo "  - 生产环境请务必使用强密钥和HTTPS"
echo "  - 端口被占用时会自动检测并提供可用端口"
echo ""

if [ "$FLASK_ENV" = "production" ]; then
    echo -e "${RED}⚠️  生产环境安全检查清单:${NC}"
    echo "  [ ] 已设置强随机密钥"
    echo "  [ ] 已配置具体的 CORS 域名"
    echo "  [ ] 已配置 HTTPS"
    echo "  [ ] 已关闭调试模式"
    echo "  [ ] 已配置生产数据库"
    echo "  [ ] 端口已正确配置且未被占用"
    echo ""
fi

read -p "按回车键继续..."

